//
//  main.c
//  C_Study
//
//  Created by rui on 12-6-30.
//  Copyright (c) 2012年 Wang Rui. All rights reserved.
//

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <unistd.h> 

/*
 @要点：静态队列(是循环队列,用数组实现)
 */

typedef unsigned int bool;
#define true 1;
#define false 0;

#undef DEBUG
#define DEBUG 1


typedef struct Queue {
	int *pBase;
	int front;
	int rear;
	int length;
}Queue;

void init(Queue *queue,int len){
	assert(NULL != queue);
	queue->pBase = (int *)malloc(sizeof(int)*(len+1));//此处加一是因为长为n的队列满时，实际按得是n-1算。
	
	if (queue->pBase == NULL) {
		exit(-1);
	}
	
	queue->front = queue->rear = 0;	
	queue->length = len+1;
}

bool is_empty(Queue *queue){
	assert(NULL != queue);
	return queue->front == queue->rear;
}

bool is_full(Queue *queue){
	assert(NULL != queue);
	return ((queue->rear+1)%(queue->length) == queue->front);
}

bool in_queue(Queue *queue,int inVal){
	assert(NULL != queue);
	if (is_full(queue)) {
		return false;
	}
	
	queue->pBase[queue->rear] = inVal;
	queue->rear = (queue->rear+1)%(queue->length);
	
	return true;
}

bool out_queue(Queue *queue,int *outVal){
	assert(NULL != queue && NULL != outVal);
	
	if (is_empty(queue)) {
		return false;
	}
	
	*outVal = queue->pBase[queue->front];
	queue->front = (queue->front+1)%(queue->length);
	
	return true;
}

void travel_queue(Queue *queue){
	assert(NULL != queue);
	
	printf("Queue:");
	int p = queue->front;
	while (p != queue->rear) {
		int num = queue->pBase[p];
		printf("%d ",num);
		p = (p+1)%(queue->length);
	}
	
	printf("\n");
}

/**********************************
 *@ main函数
 **********************************/
int main(int argc, const char * argv[])
{
	Queue q;
	init(&q,5);
	
	in_queue(&q, 5);
	in_queue(&q, 10);
	in_queue(&q, 3);
	in_queue(&q, 3);
	in_queue(&q, 7);
	travel_queue(&q);
	
	int val;
	
	out_queue(&q, &val);
	printf("%d\n",val);
	
	out_queue(&q, &val);
	printf("%d\n",val);

	in_queue(&q, 28);
	
	travel_queue(&q);
	
	return 0;
}

